import { HttpClient, HttpRequest, HttpEvent, HttpEventType, HttpHeaders } from '@angular/common/http';
import { Component, Input, OnInit, SimpleChange } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { FcsService } from 'app/service/fcs.service';
import { Environment } from 'environments/environment';
import { NzMessageService } from 'ng-zorro-antd';
import { FormArray, FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { Function } from "../../../../shared-component/class/instance";
import {randomBytes} from 'crypto';

@Component({
  selector: 'app-http-invoke',
  templateUrl: './http-invoke.component.html',
  styleUrls: ['./http-invoke.component.less']
})
export class HttpInvokeComponent implements OnInit {
  @Input() groupName = '';
  @Input() groupId = '';
  @Input() functionName = '';
  @Input() functionId = '';
  @Input() versionName = 'LATEST';
  @Input() fcsInstance: Function;

  cover = false;
  loading = true;
  canInvoke = false;
  invokeHost = Environment.application.httpTriggerHost;
  invokeUrl = "";
  invokePath = "/";
  httpTrigger = {};
  httpTriggerConfig = null;

  editorOptionsEvent = {
    language: "json",
    fontFamily: 'Monaco, Menlo, "Ubuntu Mono", Consolas, source-code-pro, monospace;',
    fontSize: "16",
    theme: 'vs'
  };
  requestBody = "";

  queryForm: FormGroup;
  isLoadingInvoke = false;
  responseBody = "";
  responseHeader = {
    FcRequestId: "",
    FcStatus: -1,
    FcCodeChecksum: "",
    FcDuration: "",
    FcMaxMemoryUsage: "",
    FcLog: "",
    FcFunctionVersion: "",
  };

  constructor(
    private fcsService: FcsService,
    private msgService: NzMessageService,
    private fb: FormBuilder,
    private http: HttpClient
  ) { }

  ngOnInit() {
    this.getTrigger();
    // 添加时间戳和随机数字段
    this.queryForm.addControl('timestamp', new FormControl(Date.now()));
    this.queryForm.addControl('nonce', new FormControl(randomBytes(5).toString(36).substring(0, 9)));


    this.queryForm = this.fb.group({
      method: ['GET', [Validators.required]],
      path: ['/', [Validators.required, Validators.pattern(/^\/[\W\w]*/)]],
      requestBody: [""],
    });
  }

  ngOnChanges(changes: SimpleChange) {
    if (changes["fcsInstance"] && !changes["fcsInstance"]["firstChange"]
      && changes["fcsInstance"]["currentValue"]["versionName"] != changes["fcsInstance"]["previousValue"]["versionName"]) {
      this.getTrigger();
    }
  }

  getTrigger() {
    let that = this;
    that.loading = true;

    this.fcsService.getTriggerList(this.groupId, this.functionId, 1, 1000, "", "http").subscribe(res => {
      that.canInvoke = false;
      that.httpTrigger = {};
      that.httpTriggerConfig = null;
      that.invokeUrl = "--";

      if (res.data) {
        for (let i = 0; i < res.data.length; i++) {
          const element = res.data[i];
          if (element.targetName == that.versionName) {
            that.canInvoke = true;
            that.httpTrigger = element;
            that.httpTriggerConfig = JSON.parse(element.config);
            that.invokeUrl = `${that.invokeHost}/proxy/${element.accountId}/${element.groupName}/${element.funcName}.${element.targetName}`
            break;
          }
        }
        if (!that.canInvoke) {
          that.invokeUrl = "请先创建版本 " + that.versionName + " 对应的 HTTP 触发器";
        }
      } else {
        that.invokeUrl = "--"
      }
      that.loading = false;
    }, err => {
      that.loading = false;
    });
  }

  successFun() {
    this.msgService.success('复制成功');
  }

  run() {
    let requestBody = null;
    if (this.requestBody != "") {
      requestBody = this.requestBody;
    }

    if (!this.queryForm.valid) {
      this.msgService.error("请检查表单参数")
      return;
    }
    this.isLoadingInvoke = true;
    let method = this.queryForm.get("method").value;
    let url = this.invokeUrl.replace(/^http:\/\//, 'https://') + this.invokePath;

    let headers = new HttpHeaders();
    let token = sessionStorage.getItem('inspur_token') || '';
    if (token != "") {
      headers = headers.append("Ce-Authorization", "bearer " + token)
    }

    const req = new HttpRequest(method, url, requestBody, {
      responseType: "text",
      headers: headers,
    });

    this.http.request(req).subscribe(
      (event: HttpEvent<any>) => {
        if (event.type == HttpEventType.Response) {
          // console.log("invoke event", event);
          this.responseBody = event.body;
          this.responseHeader.FcRequestId = event.headers.get("Ce-FcRequestId");
          this.responseHeader.FcStatus = parseInt(event.headers.get("Ce-FcStatus"));
          this.responseHeader.FcCodeChecksum = event.headers.get("Ce-FcCodeChecksum");
          this.responseHeader.FcDuration = event.headers.get("Ce-FcDuration");
          let maxMemoryUsageBytes = event.headers.get("Ce-FcMaxMemoryUsage");
          this.responseHeader.FcMaxMemoryUsage = String(parseInt(maxMemoryUsageBytes) / 1024 / 1024);
          this.responseHeader.FcLog = event.headers.get("Ce-FcLog");
          this.responseHeader.FcFunctionVersion = event.headers.get("Ce-FcFunctionVersion");
          this.isLoadingInvoke = false;
        }
      },
      (error: any) => {
        console.log("invoke errror", error);
        this.isLoadingInvoke = false;
        this.msgService.error("执行失败")
        if (typeof error.error == "string") {
          this.responseBody = error.error;
        } else {
          this.responseBody = error.message;
        }
        this.responseHeader.FcStatus = error.status;
        this.responseHeader.FcLog = error.statusText;
      }
    )
  }

}
